/*!
 * http server
 * Copyright(c) purenode
 * @author yangjian102621@gmail.com
 * MIT Licensed
 */

"use strict";

//引入内置http模块
var http = require("http");
var fs = require("fs");
var mime = require("mime");
var url = require("url");

var __APP__ = null;  //app引用
var cache = {};  //静态资源缓存

function start(route, port, app) {
	
	__APP__ = app;

	http.createServer(function(req, res) {

		var pathname = url.parse(req.url).pathname;
		if ( isStaticPath(pathname) ) {
			
			serveStatic(res, pathname);
			return;
		}

		//设置编码
		req.setEncoding("utf8");
		//执行路由
		route(req, res, __APP__);


	}).listen(port);
	
	console.log("Server has started.");
}

//判断某个路径是静态资源路径
function isStaticPath(path) {
	
	for ( var key in __APP__.staticPath ) {
		if ( path.indexOf(key) != -1 ) {
			return true;
		}
	}

	return false;

}

//向客户端发送文件
function sendFile(res, filePath, fileContents) {
	res.writeHead(200, { "Content-Type": mime.lookup(filePath) });
	res.end(fileContents);
}

//这个函数导出，给主模块使用
function serveStatic(res, filePath) {

	filePath = __APP__.getConfig("APP_ROOT")+filePath;

	if ( cache[filePath] && __APP__.getConfig("static_cache") ) { //启用缓存
		
		sendFile(res, filePath, cache[filePath]);
	
	} else {

		fs.exists(filePath, function ( exists ) {
			if ( exists ) {
				
				fs.readFile(filePath, function (err, data) {
					if ( err ) {
						__APP__.page404(res);
					} else {
						cache[filePath] = data;
						sendFile(res, filePath, data);
					}
				});

			} else {

				__APP__.page404(res);
			}

		});
	}
}

//导出对象
exports.start = start;
